package com.chat.common.jwt;

import com.chat.common.exception.CommonException;
import com.chat.common.result.ResultEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static final String SECRET = "0123456789abcdef0123456789abcdef";
    private static SecretKey key = Keys.hmacShaKeyFor(SECRET.getBytes());
    private static final long EXPIRE_TIME = 86400000; // 1天

    public static String createToken(String userId,String username) {
        return Jwts.builder()
                .setSubject(String.valueOf(userId))
                .setIssuedAt(new Date())
                .claim("userId", userId)
                .claim("username",username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .signWith(key,SignatureAlgorithm.HS256)
                .compact();
    }

    public static Claims parseToken(String token) {
        if (token==null){
            throw new CommonException(ResultEnum.TOKEN_IS_NOT_EXIST.getMsg());
        }

        try{
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(key).build();
            return jwtParser.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            throw new CommonException(ResultEnum.TOKEN_IS_EXPIRED.getMsg());
        }catch (JwtException e){
            throw new CommonException(ResultEnum.JWT_ERROR.getMsg());
        }
    }
}
